package com.nj9you.sdk.pay;

import com.nj9you.sdk.utils.RSA;

import org.json.JSONObject;

/**
 * 对签名进行验证
 */
public class AlipayChecker {

    public static final int RESULT_INVALID_PARAM = 0;
    public static final int RESULT_CHECK_SIGN_FAILED = 1;
    public static final int RESULT_CHECK_SIGN_SUCCEED = 2;

    private static final String RSA_ALIPAY_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";
    private AliPayResult mPayResult;

    public AlipayChecker(AliPayResult payResult) {
        mPayResult = payResult;
    }

    /**
     * 对签名进行验证
     *
     * @return
     */
    public int checkSignV2() {
        int retVal = RESULT_CHECK_SIGN_SUCCEED;
        try {
            JSONObject jobj = new JSONObject(mPayResult.getResult());
            String signType = jobj.getString("sign_type");
            String sign = jobj.getString("sign");
            String signContent = jobj.getString("alipay_trade_app_pay_response");
            if (signType != null && signType.equalsIgnoreCase("RSA")) {
                if (!RSA.doCheck(signContent, sign, RSA_ALIPAY_PUBLIC)) {
                    retVal = RESULT_CHECK_SIGN_FAILED;
                }
            }
        } catch (Exception e) {
            retVal = RESULT_INVALID_PARAM;
        }
        return retVal;
    }
}